//
//  FlightCheckedController.m
//  ELife
//
//  Created by xiaozhi on 11-7-19.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightCheckedController.h"
#import "FlightModel.h"
#import "UIViewUtil.h"
#import "StepView.h"
#import "FlightCustomerModel.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "GetMyData.h"
#import "LoginController.h"
#import "FlightPayResult.h"
NSInteger _detailY;

@implementation FlightCheckedController
@synthesize checkedModel;

- (id)initWithCheckedModel:(FlightCheckedModel *)model
{
    self = [super initWithNibName:@"FlightCheckedController" bundle:nil];
    if (self) {
        self.checkedModel = model;
    }
    return self;

}

- (void)showAlertView:(NSString *)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
}


// 填充联系人视图 并且返回新的Y坐标
- (NSInteger)fillCustomerView:(FlightCustomerModel *)model 
               inCustomerView:(UIView *)customerView
                    atYOffset:(NSInteger)y
                      atIndex:(NSInteger)index
{
    // 登机人信息的子视图
    NSArray *childViewList = [[NSBundle mainBundle]loadNibNamed:
                              @"FlightCheckedChildView" owner:self options:nil];
    UIView *childView = [childViewList objectAtIndex:0];
    
    UILabel *nameLabel = (UILabel *)[childView viewWithTag:1];
    UILabel *idLabel = (UILabel *)[childView viewWithTag:2];
    UILabel *priceLabel = (UILabel *)[childView viewWithTag:3];
    UILabel *indexLabel = (UILabel *)[childView viewWithTag:4];
    
    [indexLabel setText:[NSString stringWithFormat:@"%d.", index + 1]];
    [nameLabel setText:model._user_name];
    [idLabel setText:model._certificate_num];
    [priceLabel setText:model._phone];
    
    NSInteger customerHei = childView.frame.size.height;
    [customerView addSubview:childView];
    
//    childView.frame = CGRectMake(20, y, 300, customerHei);
//    
//    customerView.frame = CGRectMake(customerView.frame.origin.x, customerView.frame.origin.y, customerView.frame.size.width, customerView.frame.size.height + customerHei);
    
    return y + customerHei;
}

- (NSString *)formatHourTime:(NSString *)date
{
    return [date substringFromIndex:[date length] - 6];
}

- (void)fillaDetail:(UIView *)view
{
    UILabel *flightNo = (UILabel *)[view viewWithTag:1];
    UILabel *start = (UILabel *)[view viewWithTag:3];
    UILabel *end = (UILabel *)[view viewWithTag:4];
    UILabel *price = (UILabel *)[view viewWithTag:5];
    UILabel *totoalPrice = (UILabel *)[view viewWithTag:6];
    
    FlightDetailModel *model = checkedModel.detailModel;
    [flightNo setText:[NSString stringWithFormat:@"航班/机型:%@/%@:", model.flightNO, model.planeStyle]];
    
    NSString *hourTime = [self formatHourTime:model.depDateTime];
    [start setText:[NSString stringWithFormat:@"起飞:%@ %@", hourTime, checkedModel.fromAirport]];
    
    hourTime = [self formatHourTime:model.arriDateTime];
    [end setText:[NSString stringWithFormat:@"到达:%@ %@", hourTime, checkedModel.arriveAirport]];
    
    NSInteger basePrice = [model.basePrice intValue];
    NSInteger discount = [model.discount intValue];

    double formerlyPrice = basePrice * discount / 100;
    double discountDoubleValue = (double)(discount / 10);
    
    NSString *priceStr = [NSString stringWithFormat:@"%d元", basePrice];
    if (discount < 100) {
        priceStr = [NSString stringWithFormat:@"%@(折扣价: %d元 %f折扣)", priceStr, formerlyPrice, discountDoubleValue];
    }
    
    [price setText:priceStr];
    
    NSInteger airportTax = [model.airportTax intValue];
    NSInteger fuelTax = [model.fuelTax intValue];
    NSInteger total = airportTax + fuelTax + formerlyPrice;
    [totoalPrice setText:[NSString stringWithFormat:@"%d元/%d元/%d元", total, fuelTax, airportTax]];
}

- (void)fillContact:(UIView *)view
{
    UILabel *nameLabel = (UILabel *)[view viewWithTag:1];
    UILabel *telLabel = (UILabel *)[view viewWithTag:2];
    
    FlightContactModel *model = checkedModel.contactModel;
    [nameLabel setText:model.name];
    [telLabel setText:model.phone];
    
}

- (void)fillAddress:(UIView *)view
{
    UILabel *nameLabel = (UILabel *)[view viewWithTag:1];
    UILabel *telLabel = (UILabel *)[view viewWithTag:2];
    UILabel *addressLabel = (UILabel *)[view viewWithTag:3];
    UILabel *pCodeLabel = (UILabel *)[view viewWithTag:4];
    
    FlightAddressModel *model = checkedModel.addressModel;
    [nameLabel setText:model.name];
    [telLabel setText:model.phone];
    [addressLabel setText:model.address];
    [pCodeLabel setText:model.pCode];
}

- (void)fillTotalPrice:(UIView *)view
{
    UILabel *priceLabel = (UILabel *)[view viewWithTag:1];
    [priceLabel setText:checkedModel.totalPrice];
}



- (void)fillContent:(UIView *)childView
{
    switch (childView.tag) {
        case 1001:
            [self fillaDetail:childView];
            break;
        case 1003:
            [self fillContact:childView];
            break;
        case 1004:
            [self fillAddress:childView];
            break;
        case 1005:
            [self fillTotalPrice:childView];
            break;
            
        default:
            break;
    }
}


// 在这里加载所有view 到一个scrollView
- (void)initViews
{
    const NSInteger OFFSET_Y = 5;
    const NSInteger OFFSET_X = 10;
    //    CGFloat parentWid = self.view.frame.size.width;
    //    CGFloat parentHei = self.view.frame.size.height;
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
    scrollView.backgroundColor = [UIViewUtil getCommonBg];
    self.view.backgroundColor = [UIViewUtil getCommonBg];
    StepView *stepView = [[StepView alloc] createStepViewWithStep:3];
    [scrollView addSubview:stepView];
    [stepView release];
    
    NSInteger y = stepView.frame.origin.y + stepView.frame.size.height + OFFSET_Y;
    
    NSArray *viewList = [[NSBundle mainBundle]loadNibNamed:
                         @"FlightCheckedController" owner:self options:nil];
    
    // load all child view from nib to scrollView
    for (UIView *child in viewList) {
        // 不要加入自己
        if (child == self.view) {
            continue;
        }
        [UIViewUtil viewRoundFrame:child];
        
                
        // 如果是登机人信息 需要加载登机人列表
        if (child.tag == 1002) {
            NSInteger customerY = y;
            for (NSInteger customerIndex = 0; 
                 customerIndex < [checkedModel.customerList  count]; customerIndex++) {
                FlightCustomerModel *model = [checkedModel.customerList 
                                              objectAtIndex:customerIndex];
                
                
                customerY = [self fillCustomerView:model 
                                    inCustomerView:child
                                         atYOffset:customerY
                                           atIndex:customerIndex];
            }
        } else {
            [self fillContent:child];
        }
        
        
        NSInteger hei = child.frame.size.height;
                
        [child setFrame:CGRectMake(OFFSET_X, y, child.frame.size.width, hei)];
        y += (hei + OFFSET_Y);
        
        [scrollView addSubview:child];
    }
    
    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width - 2 * OFFSET_X, y)];
    [self.view addSubview:scrollView];
    [scrollView release];
    
}


- (void)dealloc
{
    [checkedModel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initViews];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - network
// 请求登机人信息
- (void)requestPay
{
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
    /*
     action    = order_ticket
     info_id = 1   登机人
     user_id = 9300   用户id
     user_name = 刘世群  联系人姓名
     user_phone = 13811111111  联系人电话
     insurance_number = 保险份数   1-5份 ,多人用逗号隔开
     aircode = abd123  航空公司代码
     flight_no = 航班号
     bunk = 舱位代码
     air_date = 航班日期
     start_city = 出发机场三字代码
     end_city = 到达机场三字代码
     air_number = 机票张数
     start_time = 起飞时间 19:00:00
     end_time = 到达时间 21:00:00
     air_price = 机票价格(单张) 查询接口的“最便宜的机票价格”
     paid_price = 机票实付价格，(air_price＋燃油＋机场建设费)*机票张数＋保险
     plane_type = 机型
     airporttax = 机场建设费
     fueltax = 燃油费
     freight_pay = 行程单配送运费
     mail_id = 用户邮寄地址id
     strategyNo = C0000001 策略编号
     from = mobile  区分来源
     discount = 40   折扣
     */
    
    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"order_ticket" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:userid forKey:@"user_id"];
    [param setObject:checkedModel.contactModel.name forKey:@"user_name"];
    [param setObject:checkedModel.contactModel.phone forKey:@"user_phone"];
    NSMutableString *infoIds = [[NSMutableString alloc] initWithCapacity:100];
    NSMutableString *insuranceNumbers = [[NSMutableString alloc] initWithCapacity:100];
    NSInteger baoxian = 0;
    for (FlightCustomerModel *model in checkedModel.customerList) {
        [infoIds appendFormat:@"%@,", model._info_id];
        [insuranceNumbers appendFormat:@"%@,", model._insurance_number];
        baoxian += [model._insurance_price intValue] * 20;
    }
#warning need delete last ,
    
    [param setObject:infoIds forKey:@"info_id"];
    [param setObject:insuranceNumbers forKey:@"insurance_number"];
    [param setObject:checkedModel.detailModel.airCompany forKey:@"aircode"];
    [param setObject:checkedModel.detailModel.flightNO forKey:@"flight_no"];
#warning 这里暂时写死用大写Y
    [param setObject:@"Y" forKey:@"bunk"];
    [param setObject:checkedModel.detailModel.date forKey:@"air_date"];
    [param setObject:checkedModel.startCity forKey:@"start_city"];
    [param setObject:checkedModel.endCity forKey:@"end_city"];
    [param setObject:[NSString stringWithFormat:@"%d", [checkedModel.customerList count]] forKey:@"air_number"];
    [param setObject:checkedModel.detailModel.depDateTime forKey:@"start_time"];
    [param setObject:checkedModel.detailModel.arriDateTime forKey:@"end_time"];
    [param setObject:checkedModel.detailModel.basePrice forKey:@"air_price"];
    NSInteger totalPrice = [checkedModel.totalPrice intValue] + baoxian;
    [param setObject:[NSString stringWithFormat:@"%d", totalPrice]forKey:@"paid_price"];
    [param setObject:checkedModel.detailModel.planeStyle forKey:@"plane_type"];
    [param setObject:checkedModel.detailModel.airportTax forKey:@"airporttax"];
    [param setObject:checkedModel.detailModel.fuelTax forKey:@"fueltax"];
    [param setObject:@"8" forKey:@"freight_pay"];
    [param setObject:[NSString stringWithFormat: @"%d", checkedModel.mail_id] forKey:@"mail_id"];
    [param setObject:@"mobile" forKey:@"from"];
    [param setObject:checkedModel.detailModel.discount forKey:@"discount"];
    [param setObject:@"C0000001" forKey:@"strategyNo"];

    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
    
}

- (void)requestFinished:(NSData *)response
{
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* head = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    //    NSLog(@"--------body:%@", bodyElement);
    NSInteger statusCode = [[[[head elementsForName:@"returncode"] objectAtIndex:0] stringValue]intValue];
    
    NSString *resultTitle = @"支付失败!";
    NSString *msg = @"十分抱歉,本次机票未能支付成功,原因可能为您购买的机票已经售完.";

    if (statusCode == 0) {
        resultTitle = @"支付成功!";
        msg = @"您的支付已经成功了.";
    }
    
    FlightPayResult *next = [[FlightPayResult alloc] initWithMsg:msg withTitle:resultTitle];
    [self.navigationController pushViewController:next animated:YES];
    [next release];
    
    [doc release];
    [[ELifeAppDelegate App] hideProgressDialog];
}

#pragma markend

- (void)pay
{
    [self requestPay];
}

- (void) registerOver:(NSString *)text
{
    [self requestPay];
}

@end
